import { DemoBlock } from '@/components/demos-util';
import { checkAuthorize } from '@/utils/authorize';
import { getRequestInit, urlPrefix } from '@/utils/http';
import { Content, Page } from '@alita/flow';

import {
  setPageNavBar,
  setTabBarList,
  useLocation,
  useModel,
  useNavigate,
} from 'alita';
import { DotLoading, NavBar, Space } from 'antd-mobile';
import { useEffect, useState } from 'react';
import { DetailResult, OASystem } from '../types/type';
import styles from './index.less';
// import Charts from './sub/Charts';
import Nav from './sub/Nav';
// import PerformanceCharts from './sub/PerformanceCharts';
import { baogangecg } from '@/constants';

interface Categorical {
  catalog: string;
  url: string;
  count: number;
}

export default function ({ }) {
  const navigate = useNavigate();
  const location = useLocation();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [backlogList, setBacklogList] = useState<Categorical[]>([]);
  const [oaSystem, setOASystem] = useState<OASystem>();
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(0);

  function load() {
    let times = 2;
    // 加载系统对象信息 // 代码生成annotations.utils.TsCodeCreator
    const mzcer = `/api/oa-system-detail/get/1`;
    let mzcerResponse: Promise<Response> = fetch(
      `${urlPrefix}${mzcer}`,
      getRequestInit(),
    );
    mzcerResponse
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ data, code, msg }: DetailResult<OASystem>) => {
              if (code === 0) {
                setLoadOK(msg);
                setOASystem(data);
                console.log('set dataOK!');
              } else {
                setLoadFails([...loadFails, msg]);
              }
            })
            .catch((reason) => {
              setLoadFails([...loadFails, reason]);
            })
            .finally(() => {
              console.log(`${mzcer} inner finally!`);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFails([...loadFails, `请求${mzcer}时发生错误：${reason}`]);
      })
      .finally(() => {
        console.log(`${mzcer} outter finally!`);
        setLoadingTimes(--times);
      });

    //----
    const handleUrl = `/api/audit-talk-manage/get-need-handles`;

    fetch(`${urlPrefix}${handleUrl}`, getRequestInit())
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ data, code, msg }: DetailResult<Categorical[]>) => {
              if (code === 0) {
                setLoadOK(msg);
                setBacklogList(data!);
                console.log('set dataOK!');
              } else {
                setLoadFails([...loadFails, msg]);
              }
            })
            .catch((reason) => {
              setLoadFails([...loadFails, reason]);
            })
            .finally(() => {
              console.log(`${handleUrl} inner finally!`);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFails([...loadFails, `请求${handleUrl}时发生错误：${reason}`]);
      })
      .finally(() => {
        console.log(`${handleUrl} outter finally!`);
        setLoadingTimes(--times);
      });
  } // end load

  // useEffect(() => {
  //   if (authOK) {
  //     load();
  //   }
  // }, [authOK]);

  function getTitle() {
    if (baogangecg) {
      return '三锐心电云平台管理';
    }
    return `未定义APPNAME`;
  }

  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        mode: 'dark',

        pageTitle: getTitle() + '-2025-02-24-i',
        pageBackground: '#eee',
        // pageBackground: '#fff',
        // back: '返回',
        // icon: <LeftOutline />,
        // leftContent: <div>首页</div>,
        // rightContent: <div>详情</div>,
        // onLeftClick: (navigate) => {
        //   navigate(-1);
        // },
        hideNavBar: true,
      },
    });

    // setTabBarList({
    //   pagePath: location.pathname,
    //   text: '首页',
    //   iconSize: '18px',
    //   //badge: '12',
    //   onPress: () => {
    //     navigate(location.pathname, { replace: true });
    //     return '';
    //   },
    //   remove: false,
    // });
  }, []);
  const model = useModel('useAuthModel');
  useEffect(() => {
    checkAuthorize(
      (x) => setTokening(x),
      (y) => setAuthOK(y),
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  useEffect(() => {
    console.log(`authOK=${authOK}`);
  }, [authOK]);

  if (tokening) {
    return <h2>正在授权...</h2>;
  }
  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入，还有{loadingTimes}个请求...</span>
      </div>
    );
  }

  return (
    <Page>
      <Content>
        <div className={styles.header}>
          <DemoBlock padding={0}>
            <NavBar
              // left={<Button color='primary' size='mini' shape='rounded' onClick={() => navigate('/')}>首</Button>}
              right={
                <div style={{ fontSize: 24 }}>
                  <Space style={{ '--gap': '16px' }}>
                    {/* <SearchOutline /> */}
                    {/* <MoreOutline  /> */}
                    {/* <Button
                      color="primary"
                      size="mini"
                      shape="rounded"
                      onClick={() => {
                        navigate(`/`);
                      }}
                    >
                      帮助
                    </Button> */}
                  </Space>
                </div>
              }
              onBack={() => navigate(-1)}
            >
              {getTitle()}
            </NavBar>
          </DemoBlock>
        </div>

        <Nav
          title="系统测试"
          list={[
            {
              name: '我的授权',
              url: '/object-staff/current-user',
              icon: 'icon-weituoshouquan',
            },
            {
              name: '执行授权',
              url: '/object-staff-living/create?url=oa-system-staff-living&origin=1',
              icon: 'icon-jihuazhihang',
            },
            // {
            //   name: '初始化',
            //   url: '/backend/oa-system/apply',
            //   icon: 'icon-jihuazhihang',
            // },
            {
              name: '模似开机',
              url: '/device/boot',
              icon: 'icon-jihuazhihang',
            },

            {
              name: '待注册设备',
              url: '/device/need-register',
              icon: 'icon-jihuazhihang',
            },
            {
              name: '切换用户',
              url: '/temporary/clean-token',
              icon: 'icon-jihuazhihang',
            },
          ]}
        ></Nav>

        <Nav
          title="医院管理"
          list={[
            {
              name: '新增部门',
              url: '/clinical-department/create',
              icon: 'icon-weituoshouquan',
            },
            {
              name: '新增检查医生',
              url: '/doctor/create',
              icon: 'icon-weituoshouquan',
            },
            {
              name: '新增诊断组',
              url: '/diagnosis-group/create',
              icon: 'icon-weituoshouquan',
            },
            {
              name: '新增专家',
              url: '/diagnosis-group/add-member',
              icon: 'icon-weituoshouquan',
            },
          ]}
        ></Nav>

        <Nav
          title="心电图机测试"
          list={[
            {
              name: '设备登录',
              url: '/device/connect',
              icon: 'icon-weituoshouquan',
            }
          ]}
        ></Nav>

        {/* <div className={styles.backlog}>
          <div className={styles.headerBox}>
            <div className={styles.title}>
              <div className={styles.line}></div>
              待办事项汇总
            </div>
          </div>
          <div className={styles.list}>
            {backlogList.map((categorical) => {
              const { count, catalog, url } = categorical;
              return (
                <div key={catalog} className={styles.item}>
                  <div className={styles.num}>{count}</div>
                  <div className={styles.name}>{catalog}</div>
                  <div>
                    {' '}
                    <Link to={`audit/need-handle?url=${url}&title=${catalog}`}>
                      打开
                    </Link>{' '}
                  </div>
                </div>
              );
            })}
          </div>
        </div> */}
      </Content>
    </Page>
  );
}
